package com.example.p2pinvest.common;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.p2pinvest.ui.LoadingPage;
import com.example.p2pinvest.util.UIUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;

import butterknife.ButterKnife;

/**
 * @author h2tc01
 * @version 1.0.0
 * 2022/8/9
 * 所有fragment的基类,抽取方法加载公共部分
 */
public abstract class BaseFragment extends Fragment {

    private LoadingPage page;
    protected AsyncHttpClient client = new AsyncHttpClient();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        page = new LoadingPage(container.getContext()) {
            @Override
            public int layoutId() {
                return getLayoutId();
            }

            @Override
            protected void onSuccess(ResultState resultState, View view_success) {

                ButterKnife.bind(BaseFragment.this, view_success);

                //初始化title
                initTitle();

                //初始化数据
                initData(resultState.getContent());
            }

            @Override
            protected RequestParams params() {
                return getParams();
            }

            @Override
            public String url() {
                return getUrl();
            }
        };
        return page;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //fragment视图加载完毕之后调用show()
        show();
    }

    private void show() {
        page.show();
    }

    /**
     * 获取请求参数
     *
     * @return 请求参数
     */
    protected abstract RequestParams getParams();

    /**
     * 获取请求地址
     *
     * @return 请求地址
     */
    protected abstract String getUrl();

    /**
     * 初始化界面的数据
     *
     * @param content 网络请求成功后返回的json数据
     */
    protected abstract void initData(String content);

    /**
     * 初始化标题
     */
    protected abstract void initTitle();

    /**
     * 提供布局id
     *
     * @return 布局id
     */
    public abstract int getLayoutId();
}